package hz.mobileproject.pda.toolsmanager.activity;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;

import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.TimeUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.Event;
import org.xutils.view.annotation.ViewInject;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

import hz.mobileproject.pda.R;
import hz.mobileproject.pda.app.MainApp;
import hz.mobileproject.pda.entity.response.Response_loadPoliceInfo;
import hz.mobileproject.pda.entity.response.Response_login_user;
import hz.mobileproject.pda.entity.response.Rp_loadPrisonerInfo;
import hz.mobileproject.pda.listener.CustomNetCallBack;
import hz.mobileproject.pda.network.Constance;
import hz.mobileproject.pda.toolsmanager.adapter.SmallToolListAdapter;
import hz.mobileproject.pda.toolsmanager.adapter.SmallToolTypePopAdapter;
import hz.mobileproject.pda.toolsmanager.bean.request.RQ_AddSmallTool;
import hz.mobileproject.pda.toolsmanager.bean.request.RQ_SelectSmallToolHistory;
import hz.mobileproject.pda.toolsmanager.bean.request.RQ_UpdateSmallTool;
import hz.mobileproject.pda.toolsmanager.bean.response.RP_SelectSmallToolsHistory;
import hz.mobileproject.pda.toolsmanager.bean.response.RP_Small_Tool_Type;
import hz.mobileproject.pda.toolsmanager.bean.response.RP_ToolSysSet;
import hz.mobileproject.pda.toolsmanager.utils.ToolCommonHttpUtils;
import hz.mobileproject.pda.ui.base.BaseScanActivity;
import hz.mobileproject.pda.ui.view.CustomPopWindow;
import hz.mobileproject.pda.utils.HttpRqUtils;

@ContentView(R.layout.activity_tools_manager)
public class ToolManagerActivity extends BaseScanActivity {
    @ViewInject(R.id.spinner1_small_tool)
    private TextView tv_spinner1_small_tool;
    @ViewInject(R.id.tv_user_person)
    private TextView tv_user_person;
    @ViewInject(R.id.lv_small_tool_history)
    private ListView lv_small_tool_history;

    private RP_ToolSysSet mToolSystemSet;
    private Gson mGson;
    private SmallToolListAdapter mSmallToolListAdapter;
    private List<RP_Small_Tool_Type> mToolTypeList;
    //当前选中的小件工具类型
    private RP_Small_Tool_Type mSelectedToolType;
    //当前民警信息
    private Response_loadPoliceInfo mPoliceInfo;
    //当前扫码罪犯
    private Rp_loadPrisonerInfo mPrisoner;

    private static final int REQUEST_CODE_POLICE = 0x1011;
    private static final int REQUEST_CODE_PRISONER = 0x1012;

    @Override
    protected void initData() {
        setTitleText("小件管理");
        mGson = new Gson();
        mToolSystemSet = (RP_ToolSysSet) getIntent().getSerializableExtra("key");
        mSmallToolListAdapter = new SmallToolListAdapter(this, new ArrayList<RP_SelectSmallToolsHistory>());
        lv_small_tool_history.setAdapter(mSmallToolListAdapter);
        mSmallToolListAdapter.setOnBtnClickListener(onBtnClickListener);
        getSmallToolType();
        scanPolice();
    }

    @Override
    protected void onScanSucesess(int requestCode, String scanMsg) {
        LogUtils.e(scanMsg);
        switch (requestCode) {
            case REQUEST_CODE_POLICE:
                getPliceInfoFromSer(scanMsg);
                break;
            case REQUEST_CODE_PRISONER:
                getPrisonerInfoFromSer(scanMsg);
                break;
        }
    }


    @Event({R.id.spinner1_small_tool, R.id.btn_addSamllTool, R.id.btn_next_user_person})
    private void onViewClick(View v) {
        switch (v.getId()) {
            case R.id.spinner1_small_tool:
                showPopWindow(mToolTypeList, tv_spinner1_small_tool);
                break;
            case R.id.btn_addSamllTool:
                addSmallTool();
                break;
            case R.id.btn_next_user_person:
                mPrisoner = null;
                tv_user_person.setText("");
                scanAfterPolice();
                break;
        }
    }

    /**
     * lv收回报废点击事件
     */
    private SmallToolListAdapter.OnBtnClickListener onBtnClickListener = new SmallToolListAdapter.OnBtnClickListener() {
        @Override
        public void onRetrieveClick(final RP_SelectSmallToolsHistory smallToolsHistory) {
            new AlertDialog.Builder(ToolManagerActivity.this).setTitle("提示")
                    .setMessage("是否收回此工具？")
                    .setNegativeButton("取消", null)
                    .setPositiveButton("确认", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            updateSmallTool(smallToolsHistory, RQ_UpdateSmallTool.TYPE_RETRIEVE);
                        }
                    }).create().show();
        }

        @Override
        public void onScrapClick(final RP_SelectSmallToolsHistory smallToolsHistory) {
            new AlertDialog.Builder(ToolManagerActivity.this).setTitle("提示")
                    .setMessage("是否报废此工具？")
                    .setNegativeButton("取消", null)
                    .setPositiveButton("确认", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            updateSmallTool(smallToolsHistory, RQ_UpdateSmallTool.TYPE_SCRAP);
                        }
                    }).create().show();
        }
    };

    /**
     * 获取清点小件类型
     */
    private void getSmallToolType() {
        HttpRqUtils.httpGet(Constance.BASE_URL + Constance.URL_TOOL_SMALL_TOOL_TYPE, new CustomNetCallBack() {
            @Override
            public void onSuccessFromSer(int rtnCode, String rtnMsg, String data) {
                LogUtils.e(data);
                mToolTypeList = mGson.fromJson(data, new TypeToken<List<RP_Small_Tool_Type>>() {
                }.getType());
                if (mToolTypeList == null || mToolTypeList.size() == 0) {
                    ToastUtils.showLong("小件类型为空");
                    return;
                }
            }

            @Override
            public void onErrorFromSer(int rtnCode, String rtnMsg) {
                ToastUtils.showLong("获取小件类型出错，请检查网络");
            }

            @Override
            public void onErrorFromNet(Throwable ex, boolean isOnCallback) {
                ToastUtils.showLong("获取小件类型出错，请检查网络");
            }
        });
    }


    /**
     * 请求网络接口获取民警信息
     *
     * @param scanStr
     */
    private void getPliceInfoFromSer(String scanStr) {
        ToolCommonHttpUtils.getPoliceInfoFromSer(scanStr, new CustomNetCallBack() {
            @Override
            public void onSuccessFromSer(int rtnCode, String rtnMsg, String data) {
                LogUtils.e(data);
                Response_loadPoliceInfo loadPoliceInfo = mGson.fromJson(data, Response_loadPoliceInfo.class);
                if (loadPoliceInfo == null) {
                    ToastUtils.showLong("民警信息为空");
                    return;
                }
                mScanLoadingDialog.dismiss();
                mPoliceInfo = loadPoliceInfo;
                setTitleText(mPoliceInfo.getPolice_name());
                //获取记录
                selectSmallToolsHistory();
                //打开扫描
                scanAfterPolice();
            }

            @Override
            public void onErrorFromSer(int rtnCode, String rtnMsg) {
                ToastUtils.showLong("获取民警信息失败");
            }

            @Override
            public void onErrorFromNet(Throwable ex, boolean isOnCallback) {
                ToastUtils.showLong("获取民警信息失败");
                LogUtils.e(ex);
            }
        });
    }


    /**
     * 请求网络接口获取罪犯信息
     *
     * @param scanStr
     */
    private void getPrisonerInfoFromSer(String scanStr) {
        ToolCommonHttpUtils.getPrisonerInfoFromSer(scanStr, mPoliceInfo, new CustomNetCallBack() {
            @Override
            public void onSuccessFromSer(int rtnCode, String rtnMsg, String data) {
                LogUtils.e(data);
                Rp_loadPrisonerInfo loadPrisonerInfo = mGson.fromJson(data, Rp_loadPrisonerInfo.class);
                if (loadPrisonerInfo == null) {
                    ToastUtils.showLong("罪犯信息为空");
                    return;
                }
                mScanLoadingDialog.dismiss();
                mPrisoner = loadPrisonerInfo;
                tv_user_person.setText(mPrisoner.getPrisoner_name());
            }

            @Override
            public void onErrorFromSer(int rtnCode, String rtnMsg) {
                ToastUtils.showLong("获取罪犯信息失败");
            }

            @Override
            public void onErrorFromNet(Throwable ex, boolean isOnCallback) {
                ToastUtils.showLong("获取罪犯信息失败");
                LogUtils.e(ex);
            }
        });
    }


    /**
     * 查询已发放小件的记录
     */
    private void selectSmallToolsHistory() {
        RQ_SelectSmallToolHistory selectSmallToolHistory = new RQ_SelectSmallToolHistory();
        selectSmallToolHistory.setCus_number(mPoliceInfo.getCus_number() + "");
        selectSmallToolHistory.setDept_id(mPoliceInfo.getDepartment_id() + "");
        selectSmallToolHistory.setType(RQ_SelectSmallToolHistory.TYPE_GRANT);
        HttpRqUtils.httpPost(Constance.BASE_URL + Constance.URL_SMALL_TOOL_SELECT_HISTORY, selectSmallToolHistory, new CustomNetCallBack() {
            @Override
            public void onSuccessFromSer(int rtnCode, String rtnMsg, String data) {
                LogUtils.e(data);
                List<RP_SelectSmallToolsHistory> tempList = mGson.fromJson(data, new TypeToken<ArrayList<RP_SelectSmallToolsHistory>>() {
                }.getType());
                mSmallToolListAdapter.clearAdd(tempList);
                if (tempList == null || tempList.size() == 0) {
                    ToastUtils.showLong("没有已发放的记录");
                }
            }

            @Override
            public void onErrorFromSer(int rtnCode, String rtnMsg) {
                ToastUtils.showLong("获取发放记录失败(" + rtnCode + "," + rtnMsg + ")");
            }

            @Override
            public void onErrorFromNet(Throwable ex, boolean isOnCallback) {
                ToastUtils.showLong("获取发放记录失败");
                LogUtils.e(ex.toString());
            }
        });
    }

    /**
     * 插入小件管理数据(type为发放的)
     */
    private void addSmallTool() {
        if (mPoliceInfo == null) {
            ToastUtils.showShort("请先获取民警信息");
            return;
        }
        if (mPrisoner == null) {
            ToastUtils.showShort("请先获取使用人信息");
            return;
        }
        if (mSelectedToolType == null) {
            ToastUtils.showShort("请先选择发放小件工具");
            return;
        }
        RQ_AddSmallTool addSmallTool = new RQ_AddSmallTool();
        addSmallTool.setCus_number(mPoliceInfo.getCus_number() + "");
        addSmallTool.setDept_id(mPoliceInfo.getDepartment_id() + "");
        addSmallTool.setDept_name(mPoliceInfo.getDepartment_name());
        addSmallTool.setPerson_id(mPoliceInfo.getPolice_id());
        addSmallTool.setPerson_name(mPoliceInfo.getPolice_name());
        addSmallTool.setUse_person_id(mPrisoner.getPrisoner_id());
        addSmallTool.setUse_person_name(mPrisoner.getPrisoner_name());
        addSmallTool.setTool_id(mSelectedToolType.getKey());
        addSmallTool.setTool_name(mSelectedToolType.getValue());
        addSmallTool.setTime(TimeUtils.getNowString(new SimpleDateFormat(Constance.DATE_YMDHMS)));
        addSmallTool.setType(RQ_AddSmallTool.TYPE_GRANT);
        addSmallTool.setRecord_id("");
        HttpRqUtils.httpPost(Constance.BASE_URL + Constance.URL_SMALL_TOOL_ADD_TOOL, addSmallTool, new CustomNetCallBack() {
            @Override
            public void onSuccessFromSer(int rtnCode, String rtnMsg, String data) {
                LogUtils.e(data);
                ToastUtils.showShort("添加成功");
                selectSmallToolsHistory();
            }

            @Override
            public void onErrorFromSer(int rtnCode, String rtnMsg) {
                ToastUtils.showLong("添加失败(" + rtnCode + "," + rtnMsg + ")");
            }

            @Override
            public void onErrorFromNet(Throwable ex, boolean isOnCallback) {
                ToastUtils.showLong("添加失败");
                LogUtils.e(ex.toString());
            }
        });
    }

    /**
     * 修改小件工具状态
     *
     * @param smallToolsHistory
     * @param type
     */
    private void updateSmallTool(RP_SelectSmallToolsHistory smallToolsHistory, final int type) {
        RQ_UpdateSmallTool rq_updateSmallTool = new RQ_UpdateSmallTool();
        rq_updateSmallTool.setCus_number(smallToolsHistory.getCus_number());
        rq_updateSmallTool.setDept_id(smallToolsHistory.getDept_id());
        rq_updateSmallTool.setDept_name(smallToolsHistory.getDept_name());
        rq_updateSmallTool.setPerson_id(smallToolsHistory.getPerson_id());
        rq_updateSmallTool.setPerson_name(smallToolsHistory.getPerson_name());
        rq_updateSmallTool.setUse_person_id(smallToolsHistory.getUse_person_id());
        rq_updateSmallTool.setUse_person_name(smallToolsHistory.getUse_person_name());
        rq_updateSmallTool.setTool_id(smallToolsHistory.getTool_id());
        rq_updateSmallTool.setTool_name(smallToolsHistory.getTool_name());
        rq_updateSmallTool.setRecord_id(smallToolsHistory.getFk_record_id());
        rq_updateSmallTool.setTsr_record_id(smallToolsHistory.getRecord_id());
        rq_updateSmallTool.setTime(TimeUtils.getNowString(new SimpleDateFormat(Constance.DATE_YMDHMS)));
        rq_updateSmallTool.setType(type);
        HttpRqUtils.httpPost(Constance.BASE_URL + Constance.URL_SMALL_TOOL_UPDATE_TOOL, rq_updateSmallTool, new CustomNetCallBack() {
            @Override
            public void onSuccessFromSer(int rtnCode, String rtnMsg, String data) {
                switch (type) {
                    case RQ_UpdateSmallTool.TYPE_RETRIEVE:
                        ToastUtils.showShort("回收成功");
                        break;
                    case RQ_UpdateSmallTool.TYPE_SCRAP:
                        ToastUtils.showShort("报废成功");
                        break;
                }
                selectSmallToolsHistory();
            }

            @Override
            public void onErrorFromSer(int rtnCode, String rtnMsg) {
                ToastUtils.showLong("修改小件工具状态失败(" + rtnCode + "," + rtnMsg + ")");
            }

            @Override
            public void onErrorFromNet(Throwable ex, boolean isOnCallback) {
                ToastUtils.showLong("修改小件工具状态失败");
                LogUtils.e(ex.toString());
            }
        });
    }

    /**
     * 弹出选择项popwindow
     *
     * @param toolTypes
     * @param showAsDropDownView
     */
    private void showPopWindow(final List<RP_Small_Tool_Type> toolTypes, final View showAsDropDownView) {
        if (toolTypes == null || toolTypes.size() <= 0) {
            ToastUtils.showShort("没有可选择的数据");
            return;
        }
        View contentView = LayoutInflater.from(this).inflate(R.layout.pop_custom_list, null);
        //处理popWindow 显示内容
        ListView listView = (ListView) contentView.findViewById(R.id.lv_dialog);
        SmallToolTypePopAdapter adapter = new SmallToolTypePopAdapter(this, toolTypes);
        listView.setAdapter(adapter);
        //创建并显示popWindow
        final CustomPopWindow mListPopWindow = new CustomPopWindow.PopupWindowBuilder(this)
                .setView(contentView)
                .size(showAsDropDownView.getWidth(), ViewGroup.LayoutParams.WRAP_CONTENT)//显示大小
                .create()
                .showAsDropDown(showAsDropDownView, 0, 0);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                mListPopWindow.dissmiss();
                ((TextView) showAsDropDownView).setText(toolTypes.get(position).getValue());
                switch (showAsDropDownView.getId()) {
                    case R.id.spinner1_small_tool:
                        mSelectedToolType = toolTypes.get(position);
                        break;
                }
            }
        });
    }


    /**
     * ====================================扫描流程=========================================
     */
    private void scanPolice() {
        //是否需要扫描民警
        if (RP_ToolSysSet.TSS_CALL_TYPE_SCAN_USER == mToolSystemSet.getCall_type()) {
            //扫民警
            openScan(REQUEST_CODE_POLICE, mToolSystemSet, "请扫描民警条码");
        } else if (RP_ToolSysSet.TSS_CALL_TYPE_LOGIN_USER == mToolSystemSet.getCall_type()) {
            //使用登录民警信息
            mPoliceInfo = new Response_loadPoliceInfo();
            Response_login_user loginUser = MainApp.getInstance().getLoginUser();
            mPoliceInfo.setCus_number(loginUser.getCus_number());
            mPoliceInfo.setDepartment_id(loginUser.getDepartment_id());
            mPoliceInfo.setDepartment_name(loginUser.getDepartment_name());
            mPoliceInfo.setPolice_code(loginUser.getPolice_code());
            mPoliceInfo.setPolice_id(loginUser.getPolice_id());
            mPoliceInfo.setPolice_name(loginUser.getPolice_name());
            //接着扫描
            scanAfterPolice();
        }
    }

    private void scanAfterPolice() {
        //扫描使用人
        openScan(REQUEST_CODE_PRISONER, mToolSystemSet, "请扫描使用人");
    }

}